package com.alogic.xscript.plugins;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.formula.DefaultFunctionHelper;
import com.anysoft.formula.Expression;
import com.anysoft.formula.Parser;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;

/**
 * While语句
 * @author yyduan
 * @since 1.6.12.12 [20181207 duanyy] <br>
 *
 * @version 1.6.13.23 [20201030 duanyy] <br>
 * - 优化xscript的日志机制  <br>
 */
public class While extends Segment{
	protected Expression expr = null;
	protected String $break = "true";
	public While(String tag, Logiclet p) {
		super(tag, p);
	}	
	
	@Override
	public void configure(Properties p){
		super.configure(p);
		String formula = PropertiesConstants.getString(p,"expr","",true);
		if (StringUtils.isNotEmpty(formula)){
			Parser parser = new Parser(new DefaultFunctionHelper(null));			
			expr = parser.parse(formula);
		}
		$break = PropertiesConstants.getRaw(p,"break",$break);
	}

	@Override
	protected void onExecute(XsObject root,XsObject current, LogicletContext ctx,
			ExecuteWatcher watcher) {
		if (expr != null){
			try {
				while (true){
					String value = expr.getValue(ctx).toString();
					if (!BooleanUtils.toBoolean(value)){
						break;
					}
					super.onExecute(root, current, ctx, watcher);
				}
			}catch (Exception ex){
				log(ExceptionUtils.getStackTrace(ex),LOG_ERROR);
			}
		}else{
			while (true){
				super.onExecute(root, current, ctx, watcher);
				if (PropertiesConstants.transform(ctx,$break,true)){
					break;
				}
			}
		}
	}	
}